//
// Created by dddgzc on 2025/1/26.
//

#include "../include/PeashooterPlayer.h"

#include "PeaBullet.h"

PeashooterPlayer::PeashooterPlayer() {

    this->animationIdleRight.setAtlas(peashooterIdleRightAtlas);
    this->animationIdleLeft.setAtlas(peashooterIdleLeftAtlas);
    this->animationRunLeft.setAtlas(peaShooterRunLeftAtlas);
    this->animationRunRight.setAtlas(peaShooterRunRightAtlas);
    this->animationAttackExLeft.setAtlas(peaShooterAttackExLeftAtlas);
    this->animationAttackExRight.setAtlas(peaShooterAttackExRightAtlas);
    this->animationDieRight.setAtlas(peashooterDieRightAtlas);
    this->animationDieLeft.setAtlas(peashooterDieLeftAtlas);

    this->animationIdleRight.setInterval(80);
    this->animationIdleLeft.setInterval(80);
    this->animationRunRight.setInterval(80);
    this->animationRunLeft.setInterval(80);
    this->animationAttackExLeft.setInterval(80);
    this->animationAttackExRight.setInterval(80);
    this->animationDieRight.setInterval(150);
    this->animationDieLeft.setInterval(150);

    this->animationDieRight.setIsLoop(false);
    this->animationDieLeft.setIsLoop(false);

    this->attackExTimer.setWaitTime(this->attackExDuration);
    this->attackExTimer.setIsOneShot(true);
    this->attackExTimer.setCallback([&]() {
        isAttackingEx = false;
    });

    this->spwanPeaExTimer.setWaitTime(100); // 要比正常产生子弹快
    this->spwanPeaExTimer.setIsOneShot(false);
    this->spwanPeaExTimer.setCallback([&]() {
        this->spawnPeaShooter(peaExSpeed);
    });

    attackCd = 100;
}

void PeashooterPlayer::spawnPeaShooter(float speed) {
    Bullet* bullet = new PeaBullet();
    Vector2 bulletPosition, bulletVelocity;
    const Vector2 bulletSize = bullet->getSize();
    bulletPosition.x = isFacingRight ? position.x + width - bulletSize.x / 2 : position.x - bulletSize.x / 2;
    bulletPosition.y = position.y + 10;

    bulletVelocity.x = isFacingRight ? speed : -speed;
    bulletVelocity.y = 0;

    bullet->setPosition(bulletPosition.x, bulletPosition.y);
    bullet->setVelocity(bulletVelocity.x, bulletVelocity.y);
    bullet->setCollideTarget(playerID == PlayerID::PLAYER_1 ? PlayerID::PLAYER_2 : PlayerID::PLAYER_1);
    bullet->setCallback([&]() {
       mp += 25;
    });

    bullets.push_back(bullet);
}

void PeashooterPlayer::onAttack() {
    spawnPeaShooter(peaSpeed);
}

void PeashooterPlayer::onAttackEx() {
    isAttackingEx = true;
    attackExTimer.resetTime();
    isFacingRight ? animationAttackExRight.reset() : animationAttackExLeft.reset();
}

void PeashooterPlayer::onUpdate(int delta) {
    Player::onUpdate(delta);
    if (isAttackingEx) {
        camera.shake(5, 100);
        attackExTimer.onUpdate(delta);
        spwanPeaExTimer.onUpdate(delta);
    }
}
